<?php
/**
 * 
 * Copyright (c) 2008 Jerry Jalava <jerry.jalava@gmail.com>
 * Licensed under the GPLv3 license
 * http://www.gnu.org/licenses/gpl.html
 * 
 */

class couchdb_views_view extends couchdb_transport
{
    protected $name;
    protected $args = '';
    protected $data = null;
    
    private $static_views;
    
    public function __construct($name, $configuration)
    {
        if (empty($name))
        {
            throw new couchdb_view_exception('No view name given!');
        }

        parent::__construct($configuration);
        
        $this->name = $name;
        
        $this->static_views = array( '_all_docs' );
    }
    
    public function get()
    {
        return $this->execute("_design/{$this->name}");
    }
    
    public function exists()
    {
        if (   in_array($this->name, $this->static_views)
            || $this->name == '_temp_view')
        {
            return true;
        }
        
        try
        {
            $prefix = '_design';
            $suffix = '?revs_info=true';
            if (strpos($this->name, '/') !== false)
            {
                $prefix = '_view';
                $suffix = '';
            }
            
            $this->execute("{$prefix}/{$this->name}{$suffix}");
            return ($this->lastStatusCode == 200);            
        }
        catch (couchdb_transport_exception $e)
        {
            throw new couchdb_view_exception("View {$this->name} not found.");
        }
        
        return false;
    }
    
    public function set_args($args=null)
    {
        if (is_null($args))
        {
            return;
        }
        
        if (   is_array($args)
            && !isset($args['views']))
        {
            $this->args = '?';
            foreach ($args as $key => $value)
            {
                $value = rawurlencode($value);
                $this->args .= "{$key}={$value}&";
            }
            $this->args = substr($this->args, 0, -1);
        }
        else if(   is_array($args)
                && isset($args['views']))
        {
            $this->data = json_encode($args);
        }
        else
        {
            $this->data = json_encode($args);
        }
    }
    
    public function run($create_mode=false)
    {        
        if (in_array($this->name, $this->static_views))
        {
            return $this->execute("{$this->name}{$this->args}");
        }
        
        if (   $this->name == '_temp_view'
            && !is_null($this->data))
        {
            return $this->execute("{$this->name}{$this->args}", 'POST', json_decode($this->data));
        }

        if ($create_mode)
        {
            return $this->execute("_design/{$this->name}", 'PUT', $this->data);
        }
        
        return $this->execute("_view/{$this->name}{$this->args}");
    }
}

?>